<template>
	<div class="comments">
		<h2>书籍评论</h2>

		<!-- 展示评论列表 -->
		<div v-for="(comment, index) in comments" :key="index" class="comment">
			<p>用户名：{{ comment.username }}</p>
			<p>评论内容：{{ comment.content }}</p>
		</div>

		<!-- 添加评论表单 -->
		<form @submit.prevent="addComment">
			<textarea v-model="newComment" placeholder="请输入评论内容"></textarea>
			<!-- <button @click="addComment">添加评论</button> -->
			<button type="submit">添加评论</button>
		</form>
	</div>
</template>

<script>
import { useUsersStore } from '@/store/user.js';
import axios from "axios";

	export default {
		data() {
			return {
				comments: [],
				newComment: ''
			};
		},
		mounted() {
			this.getComments();
		},
		computed: {
			usersStore() {
				return useUsersStore();
			}
		},
		methods: {
			getComments() {
				if (!this.usersStore.token) {
					alert('请先登录');
					return;
				}
				const bookId = this.$route.params.bookId;
				axios.get(`http://127.0.0.1:8080/v1/book/${bookId}/comments`)
					.then(response => {
						this.comments = response.data.comments;
					})
					.catch(error => {
						console.log(error);
					});
			},


			addComment() {



				// const userId = this.usersStore.token;    //获取的是token
				const myUser = JSON.parse(localStorage.getItem('my_user'));
				const userId = myUser.name;
				console.log("这个是登录用户",userId)
				
				const bookId = this.$route.params.bookId;
				console.log("这个是书籍id",bookId)
				
				const content = this.newComment;
				console.log("这个是评论",content)
				const token = JSON.parse(localStorage.getItem('my_user')).token;
				console.log("这个是token",myUser.token)
				if (localStorage.hasOwnProperty("my_user") && myUser.token) {
								axios.defaults.headers.common["token"] = token
								console.log(JSON.parse(localStorage.getItem("my_user")).token)//Authorization
							
				}
				console.log(userId)
				// 创建 axios 请求实例
				axios.post(`http://127.0.0.1:8080/v1/book/${bookId}/comments`, {
						my_user: userId,
						bookId,
						content
					}				
					)
				
					.then(response => {
						this.newComment = '';
						this.getComments();
					})
					.catch(error => {
						console.log(error);
					});
			}
		}
	};
</script>

<style scoped>
	.comments {
		text-align: center;
	}

	.comment {
		margin-bottom: 10px;
	}
</style>